from django.contrib.sessions.models import Session
import base64
import httplib
import logging
import logging.handlers

import settings

log = logging.getLogger('auth')
log.setLevel(level=settings.LOG_LEVEL)
handler = logging.handlers.RotatingFileHandler(settings.LOG_FILE, maxBytes=settings.LOG_FILE_SIZE)
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
log.addHandler(handler)

SESSION_CREDENTIALS = 'auth_credentials'

def gen_credentials(username, password):
    method = 'Basic '
    up = username + ':' + password
    up_enc = base64.encodestring(up)
    credentials = method + up_enc
    return credentials[:-1]

def authenticate(username, password):
    credentials = gen_credentials(username, password)
    httpconn = httplib.HTTPConnection(settings.server, settings.port)
    httpconn.request('OPTIONS', '/', '', {'Authorization':credentials, 'User-Agent':'Boxlet'})
    r = httpconn.getresponse()
    body = r.read()
    if r.status == 200:
        return True
    else:
        log.debug('Login as %s failed.' % username)
        log.debug(body)
        return False

def login(request, username, password):
    credentials = gen_credentials(username, password)
    request.session[SESSION_CREDENTIALS] = (username, password, credentials)
    request.user = credentials

def logout(request):
    request.session[SESSION_CREDENTIALS] = None
    request.user = None

def is_authenticated(request):
    if SESSION_CREDENTIALS in request.session and request.session[SESSION_CREDENTIALS]:
        request.user = request.session[SESSION_CREDENTIALS][2]
        return True
    else:
        request.user = None
        return True
